package org.magicbox.qjunTPO.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.magicbox.qjunTPO.common.lang.Result;
import org.magicbox.qjunTPO.entity.*;
import org.magicbox.qjunTPO.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 欢迎添加科技实践队粉丝群：690849711
 * @since 2021-11-17
 */
@RestController
@RequestMapping("/apply-all")
public class ApplyAllController {
    @Autowired
    ApplyAllService applyAllService;

    @Autowired
    UserService userService;

    @Autowired
    SysMessageService sysMessageService;

    @Autowired
    DeskusertypeService deskusertypeService;


    /**
     * 添加申请 申请暂时只分为两种 申请入队 和  申请自习室
     * 当已经存在申请时不允许申请
     *
     * @param apply 申请表
     * @return 结果
     */
    @PreAuthorize("hasAnyRole('LV1')")  //只允许非科队成员发起的申请（但是必须是注册了学号的用户
    @RequestMapping(value = "/addLv1", method = RequestMethod.POST)
    public Result addApplyLv1(@Validated @RequestBody ApplyAll apply) {
        Integer uid;//获取用户的id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        uid = Integer.valueOf(authentication.getName());

        String applyClass = apply.getApplyClass();//获取申请类型
        //验证是否已经存在申请
        boolean exApply = applyAllService.exApply(new ApplyAll().setApplyClass(applyClass).setUid(uid));
        if (!exApply) return Result.fail("你已经申请过啦,请等待审核");
//        if(byId==null) return Result.fail("用户不存在");  上面只要获取到了就一定有用户
        apply.setApplyType("等待审核");                 //初始化申请状态
        apply.setApplyCreate(LocalDateTime.now());      //初始化申请提交时间
        apply.setUid(uid);
        switch (applyClass) {                            //预留给其他申请
            case "申请入队":

                //保存申请信息
                try {
                    applyAllService.save(apply);
                    return Result.success("申请成功");
                } catch (Exception e) {
                    return Result.fail("申请失败,请重试");
                }
        }
        return Result.fail("申请失败");
    }

    /**
     * 针对科队成员的申请
     *
     * @param apply 申请表
     * @return
     */
    @PreAuthorize("hasAnyRole('LV2','LV3')")  //只允许科队成员发起的申请
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addApplyLv2(@Validated @RequestBody ApplyAll apply) {

        Integer uid;//获取用户的id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        uid = Integer.valueOf(authentication.getName());

        String applyClass = apply.getApplyClass();//获取申请类型

        //验证是否已经存在申请
        boolean exApply = applyAllService.exApply(new ApplyAll().setApplyClass(applyClass).setUid(uid));
        if (!exApply) return Result.fail("你已经申请过啦,请等待审核");

        apply.setApplyType("等待审核");                 //初始化申请状态
        apply.setApplyCreate(LocalDateTime.now());      //初始化申请提交时间
        apply.setUid(uid);

        switch (applyClass) {
            case "申请自习室":
                //查看用户是否是科队成员
//                Integer marker = byId.getMarker();
//                if(!marker.equals(2)&!marker.equals(4)) return Result.fail("请先申请成为科技实践队成员");  现在已经不需要这些了

                //保存申请信息
                try {
                    applyAllService.save(apply);
                    return Result.success("申请成功");
                } catch (Exception e) {
                    e.printStackTrace();
                    return Result.fail("恐怕是申请失败了");
                }
        }
        return Result.fail("申请失败");
    }

    /**
     * 获取等待审核的申请
     *
     * @param pageNumber 页码
     * @return 20条
     */
    @PreAuthorize("hasAnyAuthority('UserPower')")
    @RequestMapping("/pageWait/{type}/{pageNumber}")
    public Result pageApply(@PathVariable("pageNumber") Integer pageNumber, @PathVariable("type") int type) {
        try {
            IPage pageData = applyAllService.getApply(type, pageNumber, "等待审核");
            return Result.success(pageData);

        } catch (Exception e) {
            return Result.fail("无法获取");
        }
    }


    @PreAuthorize("hasAnyAuthority('UserPower')")
    @RequestMapping("/pageNotWait/{type}/{pageNumber}")
    public Result pageNotWait(@PathVariable("pageNumber") Integer pageNumber, @PathVariable("type") int type) {
        try {
            IPage pageData = applyAllService.getApply(type, pageNumber, "已阅");
            return Result.success(pageData);

        } catch (Exception e) {
            return Result.fail("无法获取");
        }
    }

    /**
     * 通过uid获取其所有申请
     *
     * @return 所有申请
     */
    @RequestMapping(value = "/getMeApply")
    public Result getMeApply() {

        Integer uid;//获取用户的id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        uid = Integer.valueOf(authentication.getName());

        List<ApplyAll> res = applyAllService.list(new QueryWrapper<ApplyAll>().eq("uid", uid));
        return Result.success(res);
    }


    /**
     * 管理员查看用户申请 查看的同时如果是第一次查看立即修改申请状态 为"已阅"
     *
     * @param applyid 申请id
     * @return apply
     */
    @PreAuthorize("hasAnyAuthority('UserPower')")
    @ResponseBody
    @RequestMapping(value = "/getById", method = RequestMethod.POST)
    public Result getById(@PathParam("applyid") Integer applyid) {
        ApplyAll applyAll = applyAllService.getById(applyid);
        if (applyAll == null) return Result.fail("不存在");
        if (applyAll.getApplyType().equals("等待审核")) {
            applyAll.setApplyType("已阅");
            applyAllService.updateById(applyAll);
            String msg = "您的申请已被相关管理员阅读，请等待审核，关注审核结果。";
            //获取当前管理员的id
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Integer suid = new Integer(authentication.getName());
            SysMessage sysMessage = new SysMessage(suid, applyAll.getUid(), msg, 2, applyAll.getApplyid().longValue());
            sysMessageService.addSysMsg(sysMessage);
        }
        return Result.success(applyAll);
    }

    /**
     * 审核申请
     * 给用户发送系统消息
     * 分配申请的资源
     *
     * @param applyAll
     * @return
     */
    @PreAuthorize("hasAnyAuthority('UserPower')")
    @RequestMapping(value = "/toExamine/{resouceID}", method = RequestMethod.POST)
    public Result toExamine(@PathVariable("resouceID") Integer resouceID, @Validated @RequestBody ApplyAll applyAll) {
        //获取对应的申请
        ApplyAll applyGetById = applyAllService.getById(applyAll.getApplyid());
        //获取申请的用户id
        Integer uid = applyGetById.getUid();

        //获取当前管理员账号
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Integer suid = new Integer(authentication.getName());
        switch (applyGetById.getApplyClass()) {
            case "申请入队":
                if (applyAll.getApplyType().equals("通过")) {

                    //修改用户marker
                    userService.updateMarkerById(uid, 2);

                    //发送系统消息
                    SysMessage sysMessage = new SysMessage(suid, uid, "您的申请已被通过", 2, applyAll.getApplyid().longValue());
                    sysMessageService.addSysMsg(sysMessage);

                    //修改apply状态
                    applyAllService.updateById(applyAll);

                    return Result.success("申请已被通过！");
                } else if (applyAll.getApplyType().equals("不通过")) {
                    //发送系统消息
                    SysMessage sysMessage = new SysMessage(suid, uid, "您的申请未被通过", 2, applyAll.getApplyid().longValue());
                    sysMessageService.addSysMsg(sysMessage);
                    //修改apply状态
                    applyAllService.updateById(applyAll);
                }
                break;
            case "申请自习室":
                if (applyAll.getApplyType().equals("通过")) {
                    //分配资源
                    Deskusertype deskusertype = new Deskusertype(resouceID, uid);
                    deskusertypeService.resoursceAllocation(deskusertype);

                    //发送系统消息
                    SysMessage sysMessage = new SysMessage(suid, uid, "您的申请已被通过,桌号:"+resouceID
                            , 6, resouceID.longValue());
                    sysMessageService.addSysMsg(sysMessage);

                    //修改apply
                    applyAllService.updateById(applyAll);
                    return Result.success("申请已被通过！");
                }else if (applyAll.getApplyType().equals("不通过")) {
                    //发送系统消息
                    SysMessage sysMessage = new SysMessage(suid, uid, "您的申请已被通过,分配的桌子桌号为:"+resouceID
                            , 6, resouceID.longValue());
                    sysMessageService.addSysMsg(sysMessage);

                    //修改apply状态
                    applyAllService.updateById(applyAll);
                }
        }
        return Result.fail("申请未被通过！");
    }


    /**
     * 获取申请列表
     *
     * @param pageNumber 页码
     * @return 申请列表
     */
    @PreAuthorize("hasAuthority('UserPower')")
    @RequestMapping("/page/{pageNumber}")
    public Result getPage(@PathVariable("pageNumber") Integer pageNumber) {
        Page page = new Page(pageNumber, 60);
        IPage pageData = applyAllService.page(page, new QueryWrapper<ApplyAll>().orderByDesc("apply_create"));
        return Result.success(pageData);
    }

    @PreAuthorize("hasAuthority('UserPower')")
    @RequestMapping("/okPage/{pageNumber}")
    public Result getOkPage(@PathVariable("pageNumber") Integer pageNumber) {
        Page page = new Page(pageNumber, 60);
        IPage pageData = applyAllService.page(page, new QueryWrapper<ApplyAll>().eq("apply_type", "通过").orderByDesc("apply_create"));
        return Result.success(pageData);
    }

    @PreAuthorize("hasAuthority('UserPower')")
    @RequestMapping("/noPage/{pageNumber}")
    public Result getNoPage(@PathVariable("pageNumber") Integer pageNumber) {
        Page page = new Page(pageNumber, 60);
        IPage pageData = applyAllService.page(page, new QueryWrapper<ApplyAll>().eq("apply_type", "不通过").orderByDesc("apply_create"));
        return Result.success(pageData);
    }

    /**
     * 修改申请
     *
     * @param applyAll 需要修改的申请
     * @return 结果
     */
    @RequestMapping("/update")
    public Result updateApply(@Validated @RequestBody ApplyAll applyAll) {
        //获取当前用户的id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Integer uid = new Integer(authentication.getName());

        //如果当前用户id和要修改的申请的id不一致则无权限
        if (!uid.equals(applyAll.getUid())) return Result.fail("无权限");

        //已经通过的申请无法修改
        ApplyAll byId = applyAllService.getById(applyAll.getApplyid());
        if (byId.getApplyType().equals("通过")) return Result.fail("已经通过的申请无法再修改");

        //判断申请是否存在
        if (applyAllService.exApply(applyAll)) {
            return Result.fail("不存在该申请");
        } else {

            //只要是修改过的申请都要重新等待审核
            applyAll.setApplyType("等待审核");
            applyAllService.updateById(applyAll);
            return Result.success("修改成功");
        }
    }
}
